import heapq
class Solution(object):
    def furthestBuilding(self, heights, bricks, ladders):
        n = len(heights)
        st = []
        for i in range(1, n):
            if heights[i] > heights[i - 1]:
                diff = heights[i] - heights[i - 1]
                if bricks >= diff:
                    heapq.heappush(st, -diff)
                    bricks -= diff
                else:
                    if ladders > 0:
                        ladders -= 1
                        if st:
                            if - st[0] > diff:
                                node = heapq.heappop(st)
                                bricks = bricks - node - diff
                                heapq.heappush(st, - diff)
                    else:
                        return i - 1
        return n - 1
